/**
 * by eval .
 */

import React, {Component} from 'react';
import {
  Text, 
  View,
  Image,
  TouchableOpacity,
  KeyboardAvoidingView,
  ScrollView,
  Animated,
  Alert
} from 'react-native';
import {i18n} from '../../../i18n/index';
import { scaleSize ,deviceHeight,deviceWidth} from '../../../utils/screen';
import FontText,{fontFamily} from '../../components/FontText';
import RadioGroup from '../../components/Radio/index'
import styles from './index.style';
import {TabView} from 'react-native-tab-view';
import CategeryItem from '../../components/register/CategreryItem';
import ProductView from './product';
import * as RegisterActions from '../actions/registerActions';
import RegisterCart from './cart';
import InputItem from '../../components/InputItem';
import {Toast} from 'antd-mobile-rn';

import {
  ActivityIndicator as AntActivityIndicator
} from 'antd-mobile-rn';
import { connect } from "react-redux";
import { bindActionCreators } from "redux";

class Register extends Component {
  constructor(props){
    super(props);
    this.state = {
      routes: [{
          key: "product",
        }, {
          key: "categeries"
        }
      ],
      index: 0,
      showItem:{},
      showCustom:{
        name:"",
        qty:1,
        price:0,
        options:[]
      },
      costomValue:new Animated.Value(0),
      optionValue:new Animated.Value(0),
      cartValue:new Animated.Value(0)
    }
  }
  componentDidMount(){
    this.props.getList();
  }
  render() {
    let {changeProductClassify,register,deleteCart,setEditCardItem,editCardItem} = this.props;
    let {classIndex,loading,loadingText,cartItem} = register;
    let {
      index,
      routes,
      costomValue,
      showItem,
      optionValue,
      showCustom,
      cartValue
    } = this.state;
    return (<View style={styles.container}>
        <View style = {styles.productView}>
          <View style = {styles.registerPanne}>
            <TabView
              navigationState = {this.state}
              onIndexChange={(e)=>this.onIndexChange(e)}
              useNativeDriver = {true}
              renderScene = {(e)=>this.renderScene(e)} 
              renderTabBar = {({jumpTo})=>{
                return (
                  <View style = {styles.productControl}>
                    <View style = {styles.btns}>
                      <View style = {{width:scaleSize(510)}}>
                        <RadioGroup 
                          selectIndex = {index} 
                          itemStyle = {{paddingHorizontal: scaleSize(60),}}
                          onChange = {(index)=>{
                          jumpTo(routes[index].key);
                          this.onRadioChange(index)
                        }} radios = {[i18n.t("store.register.products"),i18n.t("store.register.categories")]} />
                      </View>
                    </View>
                    <View style = {styles.searchView}>
                      <TouchableOpacity
                        style = {styles.tableView}
                        activeOpacity = {0.8}
                        >
                        <FontText style = {[styles.stext,{color:"#cfa972"}]}  font = {'book'}>Table:2</FontText>
                      </TouchableOpacity>
                      <TouchableOpacity
                        style = {[styles.tableView,styles.seatView]}
                        activeOpacity = {0.8}
                        >
                        <FontText style = {[styles.stext,{color:"#9b9b9b"}]} font = {'book'}>Seat:None</FontText>
                      </TouchableOpacity>
                    </View>
                  </View>
                );
              }}
              initialLayout={{ width: deviceWidth,height:deviceHeight }}
              />
              <View style = {styles.classify}>
                <ScrollView style ={{flex:1}} horizontal={true} >
                  {
                    register.categorys.map((item, index) => {
                      let classActive = classIndex == index ? true : false;
                      return (
                        <TouchableOpacity
                          activeOpacity = {0.8}
                          style = {[styles.classifyBtn,{backgroundColor:classActive?"#fd265d":"rgba(0,0,0,0)"}]}
                          key = {`eval_${index}`}
                          onPress = {()=>{
                            if(classIndex != index){
                              changeProductClassify(index)
                            }
                          }}
                          >
                          <FontText style = {[styles.classifyBtnText,{color:classActive?"#fff":"#000"}]}  font = {'book'}>{item.name}</FontText>
                        </TouchableOpacity>
                      )
                    })
                  }
                </ScrollView>
              </View>
          </View>
        </View>
        <View style = {styles.menu}>
          <RegisterCart 
            changeCartPress = {(item,index)=>this.changeCartPress(item,index)} 
            deleteCart = {()=>deleteCart()} 
            onLongPress = {(item)=>this.deleteCartByItem(item)}
            register = {register} />
        </View>
        <AntActivityIndicator 
          toast
          text={loadingText}
          animating={loading}
        />
        <Animated.View 
          useNativeDriver = {true}
          style = {[styles.animtedView,{transform:[{scale:optionValue}]}]}>
          <View style = {styles.optionsPop}>
              <View style = {styles.popTitle}>
                  <TouchableOpacity
                    activeOpacity = {0.8}
                    style = {styles.btnView}
                    onPressIn = {()=>this.closePop()}
                    >
                    <FontText style = {styles.popbtn} font = {"book"}>{i18n.t("btns.cancel")}</FontText>
                  </TouchableOpacity>
                  <View style = {styles.popTitleBox}>
                    <FontText style = {[styles.popbtn,{color:"#fff"}]} font = {'book'}>{i18n.t("store.register.selectoption")}</FontText>
                  </View>
                  <TouchableOpacity
                    style = {styles.btnView}
                    activeOpacity = {0.8}
                    onPressIn = {()=>this.saveOption()}
                    >
                    <FontText style = {styles.popbtn} font = {"book"}>{i18n.t("btns.save")}</FontText>
                  </TouchableOpacity>
              </View>
              <ScrollView style = {styles.popContent}>
                  {
                    Array.isArray(showItem.options) && showItem.options.map((item,oindex)=>{
                      return (
                        <View key = {`eval_${oindex}`} style = {styles.optionItem}>
                          <View style = {styles.optionTitle}>
                            {
                              item.required
                              ?<FontText style = {styles.popbtn} font = {"book"}>{i18n.t("store.register.required")} </FontText>
                              :null
                            }
                            <FontText style = {styles.titleText} font = {'book'}>{item.name}</FontText>
                          </View>
                          <View style = {styles.optionContent}>
                            {
                              item.values.map((value,vindex)=>{
                                let vid = value.server_value_id;
                                let active = item.active_id == vid;
                                if(!active){
                                  //如果是必选项，没有选择id，是第一个
                                  if(item.required && !item.active_id && vindex == 0){
                                    value.active_id = vid;
                                    active = true;
                                  }
                                }
                                return (
                                  <TouchableOpacity
                                    key = {`eval_${vindex}_${active}`}
                                    activeOpacity = {0.8}
                                    onPress = {()=>this.onValuePress(oindex,vid)}
                                    style = {[styles.optionValue,{backgroundColor:active?"#fd265d":"#cfa972"}]}
                                    >
                                    <FontText style = {styles.optiontext} font = {'book'}>{value.name}</FontText>
                                    {
                                      value.price !=0
                                      ?<FontText  style = {[styles.optiontext,{color:active?"#cfa972":"#fd265d",paddingLeft: scaleSize(9)}]} font = {'book'}>{value.price_prefix}{value.price}</FontText>
                                      :null
                                    }
                                  </TouchableOpacity>
                                );
                              })
                            }
                          </View>
                        </View>
                      );
                    })
                  }
              </ScrollView>
          </View>
        </Animated.View>
        <Animated.View 
          useNativeDriver = {true}
          style = {[styles.animtedView,{transform:[{scale:costomValue}]}]}>
          <View style = {styles.optionsPop}>
              <View style = {styles.popTitle}>
                  <TouchableOpacity
                    activeOpacity = {0.8}
                    style = {styles.btnView}
                    onPressIn = {()=>this.closeCustomPop()}
                    >
                    <FontText style = {styles.popbtn} font = {"book"}>{i18n.t("btns.cancel")}</FontText>
                  </TouchableOpacity>
                  <View style = {styles.popTitleBox}>
                    <FontText style = {[styles.popbtn,{color:"#fff"}]} font = {'book'}>{i18n.t("store.register.selectcustom")}</FontText>
                  </View>
                  <TouchableOpacity
                    style = {styles.btnView}
                    activeOpacity = {0.8}
                    onPressIn = {()=>this.saveCostom()}
                    >
                    <FontText style = {styles.popbtn} font = {"book"}>{i18n.t("btns.save")}</FontText>
                  </TouchableOpacity>
              </View>
              <KeyboardAvoidingView behavior='padding' keyboardVerticalOffset = {50} style = {[styles.popContent,{padding:scaleSize(30)}]}>
                <View style = {styles.inputItem}>
                  <FontText style = {styles.inputLable} font ={"book"}>Name</FontText>
                  <InputItem valuChange = {(val)=>this.customValue("name",val)} value = {showCustom.name} placeholder = {"Name"} style = {styles.input} />
                </View>
                <View style = {styles.inputItem}>
                  <FontText style = {styles.inputLable} font ={"book"}>Price</FontText>
                  <InputItem valuChange = {(val)=>this.customValue("price",val)} value = {showCustom.price+""} placeholder = {"Price"} style = {styles.input} />
                </View>
                <View style = {styles.inputItem}>
                  <FontText style = {styles.inputLable} font ={"book"}>Quantity</FontText>
                  <InputItem valuChange = {(val)=>this.customValue("qty",val)} value = {showCustom.qty+""} placeholder = {"Quantity"} style = {styles.input} />
                </View>
              </KeyboardAvoidingView>
          </View>
        </Animated.View>
        <Animated.View 
          useNativeDriver = {true}
          style = {[styles.animtedView,{transform:[{scale:cartValue}]}]}>
          <View style = {styles.optionsPop}>
              <View style = {styles.popTitle}>
                  <TouchableOpacity
                    activeOpacity = {0.8}
                    style = {styles.btnView}
                    onPressIn = {()=>this.tagglePop(false,cartValue)}
                    >
                    <FontText style = {styles.popbtn} font = {"book"}>{i18n.t("btns.cancel")}</FontText>
                  </TouchableOpacity>
                  <View style = {styles.popTitleBox}>
                    <FontText style = {[styles.popbtn,{color:"#fff"}]} font = {'book'}>{i18n.t("store.register.editcart")}</FontText>
                  </View>
                  <TouchableOpacity
                    style = {styles.btnView}
                    activeOpacity = {0.8}
                    onPressIn = {()=>this.editCart()}
                    >
                    <FontText style = {styles.popbtn} font = {"book"}>{i18n.t("btns.save")}</FontText>
                  </TouchableOpacity>
              </View>
              <KeyboardAvoidingView behavior='padding' keyboardVerticalOffset = {50} style = {[styles.popContent,{padding:scaleSize(30)}]}>
                <View style = {styles.inputItem}>
                  <FontText style = {styles.inputLable} font ={"book"}>Quantity</FontText>
                  <InputItem valuChange = {(val)=>editCardItem("qty",val)} value = {cartItem.qty+""} placeholder = {"Quantity"} style = {styles.input} />
                </View>
                <View style = {styles.inputItem}>
                  <FontText style = {styles.inputLable} font ={"book"}>Note</FontText>
                  <InputItem valuChange = {(val)=>editCardItem("note",val)} value = {cartItem.note+""} placeholder = {"Note"} style = {styles.input} />
                </View>
              </KeyboardAvoidingView>
          </View>
        </Animated.View>
      </View>
    );
  }
  closePop(){
    this.tagglePop(false);
  }
  closeCustomPop(){
    this.taggleCostomPop(false);
  }
  taggleCostomPop(off = false){
    this.tagglePop(off,this.state.costomValue);
  }
  changeCartPress(item,index){
    this.props.setEditCardItem(Object.assign({},item));
    this.tagglePop(true,this.state.cartValue);
  }
  editCart(){
    let {cartItem} = this.props.register;
    if(cartItem.qty =="" || !/^\d+$/.test(cartItem.qty) || cartItem.qty < 0){
      return Toast.info(i18n.t("store.register.form.qty"),3,null,false);
    }
    this.tagglePop(false,this.state.cartValue);
    if(cartItem.qty == 0){
      this.deleteCartByItem(cartItem);
    }else{
      this.props.editCart();
    }
  }
  deleteCartByItem(item){
    let {deleteCartByItem} = this.props;
    Alert.alert(i18n.t("appName"),`Delete [${item.name}] ?`,[{
      text:i18n.t("btns.cancel")
    },{
      text:i18n.t("btns.okText"),
      onPress:()=>{
        deleteCartByItem(item);
      }
    }])
  }
  tagglePop(off = false,value = this.state.optionValue){
    Animated.timing(value, {
        toValue: off?1:0,
        duration:150,
        useNativeDriver: true,
    }).start();
  }
  saveCostom(){
    let { showCustom } = this.state;
    if(showCustom.name ==""){
      return Toast.info(i18n.t("store.register.form.namerequire"),3,null,false)
    }
    if(showCustom.price == "" || !/^\d+$/.test(showCustom.price) || Number(showCustom.price) < 0){
      return Toast.info(i18n.t("store.register.form.price"),3,null,false)
    }
    if(showCustom.qty =="" || !/^\d+$/.test(showCustom.qty) || showCustom.qty < 0){
      return Toast.info(i18n.t("store.register.form.qty"),3,null,false)
    }
    this.add2cartList({
      id:0,
      price:Number(showCustom.price),
      qty:Number(showCustom.qty),
      name:showCustom.name,
      options:[],
      note:""
    });
    this.taggleCostomPop(false);
  }
  saveOption(){
    let {showItem} = this.state;
    let options = [];
    showItem.options.forEach((option)=>{
      if(option.active_id){
        option.values.forEach(value=>{
          if(option.active_id == value.server_value_id){
            options.push({
              oid:option.server_option_id,
              vid:value.server_value_id,
              name:value.name,
              qty:1,
              price:value.price_prefix=="+"?value.price:-value.price
            })
            return false;
          }
        })
      }
    })
    let product = {
      id:showItem.server_product_id,
      name:showItem.name,
      note:"",
      options:options,
      price:showItem.price,
      qty:1
    }
    this.add2cartList(product);
    this.tagglePop(false);
  }
  customValue(key,value){
    let { showCustom } = this.state;
    showCustom[key] = value;
    this.setState({
      showCustom:showCustom
    })
  }
  onValuePress(oindex,vid){
    let {showItem} = this.state;
    let item = showItem.options[oindex];
    if(item.active_id == vid && !item.required){
      item.active_id = 0;
    }else{
      item.active_id = vid;
    }
    this.setState({
      showItem:showItem
    })
  }
  onRadioChange(index){
    this.setState({
      index: index
    })
  }
  categoryOnPress(item,index){
    this.setState({
      index:0
    },()=>{
      this.onClassifyPress(index);
    })
  }
  onClassifyPress(index){
    this.props.changeProductClassify(index);
  }
  valuChange(val,key){
    this.setState({
      [key]:val
    })
  }
  onIndexChange(index){
    this.setState({
      index:index
    })
  }
  renderScene(e){
    let {key} = e.route;
    let {register,changeProductClassify} = this.props;
    switch (key) {
      case "product":
        if (register.categorys.length > 0){
          return (
            <View style = {styles.swiperBox}>
              <ProductView 
                onIndexChange = {(index) => changeProductClassify(index)}
                onItempress = {(item)=>this.productPress(item)}
                register = {register}/>
            </View>
          )
        }else{
          return (
            <View style = {styles.swiperBox}>
              <FontText font = {'book'}>empty!</FontText>
            </View>
          )
        }
      break;
      case "categeries":
      if (register.categorys.length > 0){
        return (
          <View style = {[styles.swiperBox,styles.categertBox]}>
            {
              register.categorys.map((item,index)=>{
                return (
                  <View style = {styles.categeryItem} key = {`eval_${index}`}>
                    <CategeryItem onPress = {()=>this.categoryOnPress(item,index)} {...item} />
                  </View>
                )
              })
            }
          </View>
        )
      }else{
        return (
          <View style = {styles.swiperBox}>
            <FontText font = {'book'}>empty!</FontText>
          </View>
        )
      }
      break;
      default:
        break;
    }
  }
  productPress(item){
    //商品，有分类
    if(item && Array.isArray(item.options) && item.options.length > 0){
      this.setState({
        showItem:Object.assign({},item)
      },()=>{
        this.showProductModal();
      })
      //商品无分类，直接添加
    }else if(item){
      this.add2cartList({
        id:item.server_product_id,
        name:item.name,
        note:"",
        options:[],
        price:item.price,
        qty:1
      });
    }else{
      this.taggleCostomPop(true);
    }
  }
  showProductModal(){
    this.tagglePop(true);
  }
  add2cartList(item){
    let {add2cart} = this.props;
    add2cart(item);
  }
}

export default connect(
  state => ({
    register: state.register
  }),
  dispatch => bindActionCreators(RegisterActions, dispatch)
)(Register);